const moment = require('./moment/index.js');
let config = require('./config');
console.info("config", config);
// 成功弹框
function successToast(title) {
  wx.showToast({
    title: title,
    mask: false,
    icon: 'success',
    duration: 2000
  })
}


function showToast(title) {
  wx.showToast({
    title: title,
    mask: false,
    icon: 'none',
    duration: 2000
  })
}
// 加载中弹框
function loadingToast(title = '加载中...') {
  wx.showLoading({
    title: title,
    mask: true,
    duration: 2000
  })
}

function hideToast() {
  wx.hideLoading();
  wx.hideToast();
}
function isEmpty(obj) {
  if (obj == "undefined" || obj == null || obj == "" || obj == undefined || JSON.stringify(obj) == "{}") {
    return true;
  } else {
    return false;
  }
}
function formatSeconds(s) {
  var t;
  if (s > -1) {
    var hour = Math.floor(s / 3600);
    var min = Math.floor(s / 60) % 60;
    var sec = s % 60;
    if (hour < 10) {
      t = '0' + hour + ":";
    } else {
      t = hour + ":";
    }

    if (min < 10) { t += "0"; }
    t += min + ":";
    if (sec < 10) { t += "0"; }
    t += sec.toFixed(0);
  }
  return t;
}


function trimSpace(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] == " " || array[i] == null || typeof (array[i]) == "undefined" || array[i] == "") {
      array.splice(i, 1);
      i = i - 1;

    }
  }
  return array;
}
/**
 * 音频播放时间换算
 * @param {number} value - 音频当前播放时间，单位秒
 */
function transTime(value) {
  var time = "";
  var h = parseInt(value / 3600);
  value %= 3600;
  var m = parseInt(value / 60);
  var s = parseInt(value % 60);
  if (h > 0) {
    time = formatTime(h + ":" + m + ":" + s);
  } else {
    time = formatTime(m + ":" + s);
  }
  return time;
}
/**
 * 格式化时间显示，补零对齐
 * eg：2:4  -->  02:04
 * @param {string} value - 形如 h:m:s 的字符串
 */
function formatTime(value) {
  var time = "";
  var s = value.split(":");
  var i = 0;
  for (; i < s.length - 1; i++) {
    time += s[i].length == 1 ? "0" + s[i] : s[i];
    time += ":";
  }
  time += s[i].length == 1 ? "0" + s[i] : s[i];
  return time;
}
//格式化时间
function formatDateTime(time) {
  var dd = parseInt(time / 1000 / 60 / 60 / 24, 10);
  var hh = parseInt((time / 1000 / 60 / 60) % 24, 10);
  var mm = parseInt((time / 1000 / 60) % 60, 10);
  var ss = parseInt((time / 1000) % 60, 10);
  dd = dd < 10 ? "0" + dd : dd; //天
  hh = hh < 10 ? "0" + hh : hh; //时
  mm = mm < 10 ? "0" + mm : mm; //分
  ss = ss < 10 ? "0" + ss : ss; //秒
  return mm + ":" + ss;
}

// 判断登录状态
function checkSession(url = getCurrentPageUrlWithArgs()) {
  if (wx.getStorageSync('authToken')) {

  } else {
    if (url != "pages/login/login") {
      wx.setStorageSync('backurl', url)
      wx.redirectTo({
        url: "/pages/login/login?backurl=" + encodeURIComponent(url)
      })
    }
  }
}
// 获取当前页面路径
function getCurrentPageUrlWithArgs() {
  var pages = getCurrentPages(); //获取加载的页面
  if (pages == '') {
    return 'pages/login/login'
  }
  var currentPage = pages[pages.length - 1] //获取当前页面的对象
  var url = currentPage.route //当前页面url
  var options = currentPage.options //如果要获取url中所带的参数可以查看options
  //拼接url的参数
  var urlWithArgs = url + '?'
  for (var key in options) {
    var value = options[key]
    urlWithArgs += key + '=' + value + '&'
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
  return urlWithArgs
}
// 判断是否存在http 或https
function ishttp(str) {
  var arr = ['https', 'http'];
  str = str.substring(0, 4);
  if (arr.indexOf(str) == -1) {
    return false;
  } else {
    return true;
  }
}

/**
 * 存储localStorage
 */
function setLocalStorage(key, data) {
  if (typeof data == "string") {
    wx.setStorageSync(key, data);
    return;
  }
  try {
    wx.setStorageSync(key, JSON.stringify(data));
  } catch (e) {
  }
}
/**
 * 获取localStorage
 */
function getLocalStorage(key) {
  let values = wx.getStorageSync(key);
  if (values === undefined) {
    return "";
  }
  try {
    return JSON.parse(values, null);
  } catch (e) {
    return values;
  }
}

/**
 * 删除localStorage
 */
function removeLocalStorage(name) {
  if (!name) return;
  wx.removeStorage({
    key: name,
    success: (result) => {

    },
    fail: () => { },
    complete: () => { }
  });
}

function pickupTime(goods) {
  let config = getLocalStorage("config");
  let pickTime = goods.tihuoday;
  let isContinuity = goods.isContinuity;
  //连续卖的商品
  if (isContinuity) {
    let jin = new Date();
    let year = jin.getFullYear();
    let month = jin.getMonth() + 1;
    let strDate = jin.getDate();
    let hour = jin.getHours();
    let dateNow = jin.getTime();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    //当前时间与设置的截团时间相比较
    if (config) {
      let nodeHour = config.nodeHour;
      let nodeMin = config.nodeMin;
      if (config.nodeHour >= 1 && config.nodeHour <= 9) {
        nodeHour = "0" + nodeHour;
      }
      if (config.nodeMin >= 0 && config.nodeMin <= 9) {
        nodeMin = "0" + nodeMin;
      }
      let day = (year + "-" + month + "-" + strDate + " " + nodeHour + ":" + nodeMin + ":" + "00").replace(/-/g, '/');
      let jieTime = new Date(day).getTime();
      let expectedPickTime = config.expectedPickTime;
      if (dateNow <= jieTime) {
        return Date.parse(day.replace(/-/g, '/')) / 1000 + expectedPickTime * 60;
      } else {
        jieTime += 24 * 60 * 60 * 1000;
        return jieTime / 1000 + expectedPickTime * 60;
      }
    }
  }
  if (!pickTime) {
    if (config) {
      pickTime = config.expectedPickTime;
    }
  }

  return Date.parse(goods.timeend.replace(/-/g, '/')) / 1000 + pickTime * 60;
}

function dateFormat(value, format = 'YYYY-MM-DD') {
  if (String(value).indexOf('-') != '-1') {
    value = value.replace(/-/g, '/');
  }
  if (!value) {
    return '';
  }

  if (typeof (value) === "number") {
    return moment(value * 1000).format(format);
  } else {
    return moment(value).format(format);
  }
}
function dateTimeFormat(value, format = 'MM-DD HH:mm') {
  return dateFormat(value, format);
}
function dateTimeFormatMd(value, format = 'MM月DD日 HH: mm') {
  return dateFormat(value, format);
}

function idCard(val) {
  return /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/.test(val)
}

function mobile(val) {
  return /^1[0-9]{10}$/.test(val)
}
function islogin() {
  wx.showModal({
    title: '您还未登录',
    content: '请登录再进行操作',
    showCancel: true,
    cancelText: '暂不登录',
    cancelColor: '#000000',
    confirmText: '立即登录',
    confirmColor: '#3CC51F',
    success: res => {
      if (res.confirm == true) {
        removeLocalStorage('user');
        removeLocalStorage('assistmode');
        removeLocalStorage('authToken');
        removeLocalStorage('supplier');
        removeLocalStorage('serverTime');
        removeLocalStorage('config');
        checkSession();
      }
    }
  });
}
function _momformatTime(number, format) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function OffGroup() {
  let config = getLocalStorage("config");
  let jin = new Date();
  let year = jin.getFullYear();
  let month = jin.getMonth() + 1;
  let strDate = jin.getDate();
  let hour = jin.getHours();
  let dateNow = jin.getTime();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }

  let nodeHour = config.nodeHour ? config.nodeHour : 9;
  let nodeMin = config.nodeMin ? config.nodeMin : 55;;
  if (config.nodeHour >= 1 && config.nodeHour <= 9) {
    nodeHour = "0" + nodeHour;
  }
  if (config.nodeMin >= 0 && config.nodeMin <= 9) {
    nodeMin = "0" + nodeMin;
  }
  let day = (year + "-" + month + "-" + strDate + " " + nodeHour + ":" + nodeMin + ":" + "00").replace(/-/g, '/');
  let jieTime = new Date(day).getTime();
  let time;
  if (dateNow <= jieTime) {
    time = jieTime - dateNow;
    return time;
  } else {
    jieTime += 24 * 60 * 60 * 1000;
    time = jieTime - dateNow;
    return time;
  }

}
module.exports = {
  successToast: successToast,
  showToast: showToast,
  loadingToast: loadingToast,
  hideToast: hideToast,
  isEmpty: isEmpty,
  ishttp: ishttp,
  formatSeconds: formatSeconds,
  trimSpace: trimSpace,
  transTime: transTime,
  formatDateTime: formatDateTime,
  checkSession: checkSession,
  setLocalStorage: setLocalStorage,
  getLocalStorage: getLocalStorage,
  removeLocalStorage: removeLocalStorage,
  islogin: islogin,
  idCard,
  mobile,
  _momformatTime,
  dateTimeFormat,
  dateTimeFormatMd,
  pickupTime,
  dateFormat,
  OffGroup
}